﻿using MQTTnet;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MqttDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        IMqttServer mqttServer;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btn_start_Click(object sender, RoutedEventArgs e)
        {

            mqttServer = new MqttFactory().CreateMqttServer();
            var optionsBuilder = new MqttServerOptionsBuilder()
                .WithConnectionBacklog(100)
                .WithDefaultEndpointPort(1884);
            var options = optionsBuilder.Build();
            mqttServer.ClientSubscribedTopic += MqttServer_ClientSubscribedTopic;

            mqttServer.Started += MqttServer_Started;
            mqttServer.Stopped += MqttServer_Stopped;

            mqttServer.ClientConnected += MqttServer_ClientConnected;
            mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
            
            mqttServer.StartAsync(options);         
        }

        private void MqttServer_ClientSubscribedTopic(object sender, MqttClientSubscribedTopicEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void MqttServer_ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
            this.ShowLog(e.ClientId + "Disconnecteds...");
        }

        private void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e)
        {
            this.ShowLog(e.ClientId + "Conneced..");
        }

        private void ShowLog(string msg)
        {
            tb_log.Dispatcher.BeginInvoke(new Action(() =>
            {
                tb_log.AppendText(msg+"\r\n");
                tb_log.ScrollToEnd();
            }));
           
        }

        private void MqttServer_Stopped(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void MqttServer_Started(object sender, EventArgs e)
        {
            this.ShowLog("Mqtt Server Starting....");
        }
    }
}
